package com.ticker.national;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.ticker.national.BaseAsyncTask.OnTaskListener;
import com.ticker.national.FTAParseTask.FTAInfo;
import com.ticker.national.RoomNumberParseTask.RoomInfo;
import com.ticker.national.db.DBHandler;
import com.ticker.national.twitter.MyTwitter;
import com.ticker.national.twitter.TwitterProcess;
import com.ticker.national.util.HtmlParsing;
import com.ticker.national.util.HtmlParsing.OnProcessTerminatedListener;
import com.ticker.national.util.HtmlParsing.TaskType;
import com.ticker.national.util.Log;

public class ParsingPerson extends Activity implements OnClickListener{
	
	private final String TAG = "ParsingPerson";
	
	private HtmlParsing mHtmlParser;
	private Button mBtnParty;
	private Button mBtnDetail;
	private Button mBtnSocial;
	private Button mBtnProfileImage;
	private Button mBtnLocationImage;
	private Button mBtnGetRoomNumber;
	private Button mBtnGetFTA;
	private Button mBtnSetVersion;
	private Button mBtnTwitterLogin;
	private EditText mEtVersion;
	private ArrayList<RoomInfo> mRoomInfoList;
	private ArrayList<FTAInfo> mFTAInfoList;
	private Twitter mTwitter;
	private AuthenticationCB mAuthenticationCB;
	private Intent mIntent;
	
	public interface AuthenticationCB {
		public abstract void onError();
		public abstract void onSuccess();
	}
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mBtnParty = (Button)findViewById(R.id.bt_party);
        mBtnDetail = (Button)findViewById(R.id.bt_detail);
        mBtnSocial = (Button)findViewById(R.id.bt_social);
        mBtnProfileImage = (Button)findViewById(R.id.bt_image);
        mBtnLocationImage = (Button)findViewById(R.id.bt_image_location);
        mBtnGetRoomNumber = (Button)findViewById(R.id.bt_room_num);
        mBtnGetFTA = (Button)findViewById(R.id.bt_fta);
        mBtnSetVersion = (Button)findViewById(R.id.bt_version);
        mBtnTwitterLogin = (Button)findViewById(R.id.twitterLogin);
        mEtVersion = (EditText)findViewById(R.id.et_version);
        
        mBtnParty.setOnClickListener(this);
        mBtnDetail.setOnClickListener(this);
        mBtnSocial.setOnClickListener(this);
        mBtnProfileImage.setOnClickListener(this);
        mBtnLocationImage.setOnClickListener(this);
        mBtnGetRoomNumber.setOnClickListener(this);
        mBtnGetFTA.setOnClickListener(this);
        mBtnSetVersion.setOnClickListener(this);
        mBtnTwitterLogin.setOnClickListener(this);
        
        mHtmlParser = HtmlParsing.getInstance();
        mHtmlParser.setOnProcessTerminatedListener(new OnProcessTerminatedListener() {
			
			@Override
			public void onParsingTerminated(TaskType type) {
				Log.i(TAG, "onParsingTerminated() type: " + type);
				if(type.equals(TaskType.PartyParser) || type.equals(TaskType.DetailParser)) {
					mHtmlParser.updatePersonInfoToDB();
				}
				else if(type.equals(TaskType.SocialParser)) {
					// TODO:!!!
					Log.d(TAG, "do something.!!");
					mHtmlParser.updateSocialIdToDB();
				}
				else {
					mHtmlParser.updateImageInfo(type);
					Log.d(TAG, "hello");
				}
				updateButtonEnable();
			}
			
			@Override
			public void onDBUpdatingTerminated() {
				mHtmlParser.updatePositionInfo();
			}
		});
        /*
        mHtmlParser.start(TaskType.PartyParser, false);
        */
        
        DBHandler.init(getApplicationContext());
        
        mAuthenticationCB = new AuthenticationCB() {
			
			@Override
			public void onSuccess() {
				startActivity(mIntent);
			}
			
			@Override
			public void onError() {
			}
		};
		
		mIntent = new Intent(ParsingPerson.this, TwitterProcess.class);
    }

	private void disableAllButton() {
        mBtnParty.setEnabled(false);
        mBtnDetail.setEnabled(false);
        mBtnProfileImage.setEnabled(false);
        mBtnLocationImage.setEnabled(false);
        mBtnGetRoomNumber.setEnabled(false);
        mBtnGetFTA.setEnabled(false);
        mBtnSetVersion.setEnabled(false);
        mBtnTwitterLogin.setEnabled(false);
	}
	
	private void enableAllButton() {
        mBtnParty.setEnabled(true);
        mBtnDetail.setEnabled(true);
        mBtnProfileImage.setEnabled(true);
        mBtnLocationImage.setEnabled(true);
        mBtnGetRoomNumber.setEnabled(true);
        mBtnGetFTA.setEnabled(true);
        mBtnSetVersion.setEnabled(true);
        mBtnTwitterLogin.setEnabled(true);
	}
	
	private void updateButtonEnable() {
		enableAllButton();
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.bt_party:
			// party list
			disableAllButton();
			mHtmlParser.doParse(TaskType.PartyParser);
			break;
		case R.id.bt_detail:
			disableAllButton();
			mHtmlParser.doParse(TaskType.DetailParser);
			// detail profile
			break;
			
		case R.id.bt_social:
			disableAllButton();
			mHtmlParser.doParse(TaskType.SocialParser);
			// detail profile
			break;
			
		case R.id.bt_image:
			disableAllButton();
			mHtmlParser.doDownloadImage(TaskType.ProfileImage);
			// profile image
			break;
		case R.id.bt_image_location:
			disableAllButton();
			mHtmlParser.doDownloadImage(TaskType.LocationImage);
			// location image
			break;
		case R.id.bt_room_num:
			disableAllButton();
			mRoomInfoList = new ArrayList<RoomInfo>();
			RoomNumberParseTask task = new RoomNumberParseTask(mRoomInfoList, new OnTaskListener() {
				
				@Override
				public void onTerminated() {
					Log.d(TAG, "onTerminated()");
					/**
					for(RoomInfo info : mRoomInfoList) {
						Log.d(TAG, "info: " + info);
					}
					**/
					DBHandler.getInstance().setRoomInfo(mRoomInfoList);
					updateButtonEnable();
				}
				
				@Override
				public void onError() {
				}
				
				@Override
				public void onCancel() {
				}
			});
			task.execute();
			// location image
			break;
		case R.id.bt_fta:
			getFtaInfo();
			disableAllButton();
			break;
			
		case R.id.bt_version:
			setDBVersion();
			break;
		case R.id.twitterLogin:
			twitterLogin();
			break;
		}
	}

	private void getFtaInfo() {
		mFTAInfoList = new ArrayList<FTAInfo>();
		FTAParseTask task = new FTAParseTask(mFTAInfoList, new OnTaskListener() {

			@Override
			public void onTerminated() {
				Log.d(TAG, "onTerminated()");
				for(FTAInfo info : mFTAInfoList) {
					Log.d(TAG, "info: " + info);
				}
				DBHandler.getInstance().setFTAInfo(mFTAInfoList);
				updateButtonEnable();
			}

			@Override
			public void onError() {
			}

			@Override
			public void onCancel() {
			}
		});
		task.execute();
	}

	private void twitterLogin() {
		Log.d(TAG, "twitterLogin()");
	    String authorizationUrl = null;
		mTwitter = MyTwitter.getInstance().getTwitter();
		
	    RequestToken requestToken = null;
		try {
			requestToken = mTwitter.getOAuthRequestToken();
			authorizationUrl = requestToken.getAuthorizationURL();
		} catch (TwitterException e) {
			e.printStackTrace();
		}
		
		Log.d(TAG, "authorizationUrl : " + authorizationUrl);
		MyTwitter.getInstance().setRequestToken(requestToken);
		
		
		LoginTask loginTask = new LoginTask(mAuthenticationCB);
		if(authorizationUrl != null)
			loginTask.execute(authorizationUrl);
		else 
			Log.e(TAG, "error ouccured");
	}
	
	class LoginTask extends AsyncTask<String, Void, Boolean> {
		private AuthenticationCB mCallback;
		LoginTask(AuthenticationCB cb) {
			mCallback = cb;
		}

		@Override
		protected Boolean doInBackground(String... url) {
			Log.d(TAG, "url: " + url[0]);
			HttpClient client = AndroidHttpClient.newInstance(this.getClass().getName());
			final HttpGet getRequest = new HttpGet(url[0]);
			Source source = null;
			String auth_token = null;
			
			try {
				HttpResponse response = client.execute(getRequest);
				final HttpEntity entity = response.getEntity();
				if(entity != null) {
					source = new Source(new InputStreamReader(response.getEntity().getContent(), "EUC-KR"));

					source.getAllElements();
					List<Element> form = source.getAllElements(HTMLElementName.FORM);
					List<Element> input = form.get(0).getAllElements(HTMLElementName.INPUT);
					Log.d(TAG, "input: " + input.get(0).toString());
					auth_token = input.get(0).getAttributeValue("value");
					mIntent.putExtra("AUTH_TOKEN", auth_token);
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			} finally {
				((AndroidHttpClient) client).close();
			}
			
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if(!result) {
				mCallback.onError();
			}
			else {
				mCallback.onSuccess();
			}
		}
	}

	private void setDBVersion() {
		int version = Integer.parseInt(mEtVersion.getText().toString());
		DBHandler.getInstance().getSQLiteDB().setVersion(version);
		mEtVersion.setText("");
	}
}